using Commons.Models.Functions;
using Commons.Models.OperationsContext;
using System.Collections.Generic;

namespace Commons.Services.Functions
{
	public class FunctionEvaluator : IFunctionEvaluator
	{
		public List<IVariableEvaluator> Evaluators { protected get; set; }

		public double Eval(IFunction<double, double> function, IOperationContext context)
		{
			return function.Eval(CalculateVariable(function.Var, context));
		}

		protected double CalculateVariable(string variable, IOperationContext context)
		{
			if (!string.IsNullOrEmpty(variable) && Evaluators != null)
			{
				foreach (IVariableEvaluator evaluator in Evaluators)
				{
					double? result = evaluator.Eval(variable, context);
					if (result.HasValue)
					{
						return result.Value;
					}
				}
			}

			return 0;
		}
	}
}

